﻿using System;
using System.Net;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Collections.Generic;
using Microsoft.Maps.MapControl;
using Microsoft.Maps.MapControl.Core;
using System.Linq;
using System.Xml.Linq;

namespace SMIL.Client.WPXAP.PushPin
{
    public class SMILPin : XAMLPushPin
    {
        Grid g;        
        Border b0, b1, b2, b3;
        Image im;
        TextBlock tb_title, tb_subtitle;        
        Button ob, sb, mb;
        Storyboard s;
        DoubleAnimation daw, dah;

        ComboBox views;
        ListBox details;

        SPCommunication.ASMX.SPGeoRssSISoapClient client;

        public SMILPin(MapCore map) : base(map)
        {
            LoadFromFile("SMIL.Client.WPXAP.PushPin.SMILPin.xaml");
            Loaded += new RoutedEventHandler(SMILPin_Loaded);
        }       
        
        [DefaultValue("Title")]
        public string Title { get; set; }

        [DefaultValue("Subtitle")]
        public string Subtitle { get; set; }

        public string IconUrl { get; set; }

        public string ObjectUrl { get; set; }

        public Guid Guid { get; set; }

        public string ViewName { get; set; }

        public string[] ViewNames { get; set; }

        public string ListName { get; set; }

        public string SPSiteURI { get; set; }
        
        public string SPItemID { get; set; }

        public class ItemDetail
        {
            public string fieldName { get; set; }
            public string fieldType { get; set; }
            public string fieldValue { get; set; }
        }

        public XElement Details
        {            
            set
            {
                var d = (from detail in value.Descendants("detail")
                         select new ItemDetail
                        {
                            fieldName = detail.Attribute("fieldName").Value.ToString(),
                            fieldType = detail.Attribute("type").Value.ToString(),
                            fieldValue = detail.Value.ToString()
                        });

                try
                {
                    ItemDetail id = d.First(param => param.fieldName == "ID");
                    SPItemID = id.fieldValue;
                    sb.Visibility = Visibility.Visible;
                }
                catch
                {
                    sb.Visibility = Visibility.Collapsed;
                }

                details.ItemsSource = d;
            }
        }

        public override void OnApplyTemplate()
        {
            g = FindControlChild("PART_Grid") as Grid;
            g.MouseLeave += new MouseEventHandler(g_MouseLeave);

            im = FindControlChild("PART_Image") as Image;
            im.Source = new BitmapImage(new Uri(IconUrl));
            
            tb_title = FindControlChild("PART_Title") as TextBlock;
            tb_title.Text = Title;

            tb_subtitle = FindControlChild("PART_Subtitle") as TextBlock;
            tb_subtitle.Text = Subtitle;
   
            b0 = FindControlChild("B0") as Border;
            b1 = FindControlChild("B1") as Border;
            b2 = FindControlChild("B2") as Border;
            b3 = FindControlChild("B3") as Border;   

            b0.MouseEnter += new MouseEventHandler(b0_MouseEnter);

            s = FindControlChild("PART_Storyboard") as Storyboard;
            daw = FindControlChild("PART_DoubleAnimationWidth") as DoubleAnimation;
            dah = FindControlChild("PART_DoubleAnimationHeight") as DoubleAnimation;
         
            ob = FindControlChild("PART_Openbutton") as Button;
            sb = FindControlChild("PART_Selectbutton") as Button;
            mb = FindControlChild("PART_Morebutton") as Button;

            ob.Click += new RoutedEventHandler(ob_Click);
            sb.Click += new RoutedEventHandler(sb_Click);
            mb.Click += new RoutedEventHandler(mb_Click);

            client = SPCommunication.Proxy.GetProxy;
            client.GetSPItemDetailCompleted += new EventHandler<SMIL.Client.WPXAP.SPCommunication.ASMX.GetSPItemDetailCompletedEventArgs>(client_GetSPItemDetailCompleted);

            views = FindControlChild("PART_Views") as ComboBox;
            details = FindControlChild("PART_Details") as ListBox;

            views.ItemsSource = ViewNames;
            views.SelectionChanged += new SelectionChangedEventHandler(views_SelectionChanged);            
            
            //it = FindControlChild("PART_Infotool") as InfoTool.InfoTool;
            //it.Guid = Guid;
            //it.SPSiteURI = SPSiteURI;
            //it.ViewName = ViewName;
            //it.ViewNames = ViewNames;
            //it.ListName = ListName;

            LoadAnimation();
        }

        void SMILPin_Loaded(object sender, RoutedEventArgs e)
        {
            views.SelectedItem = ViewName;         
        }

        void views_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ViewName = views.SelectedItem as string;
            GetDetails();
        }

        void mb_Click(object sender, RoutedEventArgs e)
        {
            if (b3.Visibility == Visibility.Visible)
            {
                b3.Visibility = Visibility.Collapsed;
            }
            else
            {
                GetDetails();
                b3.Visibility = Visibility.Visible;
            }
        }

        public void GetDetails()
        {
            client.GetSPItemDetailAsync(new SMIL.Client.WPXAP.SPCommunication.ASMX.ItemDetailRequest()
            {
                SiteUrl = SPSiteURI,
                SPItemGuid = Guid,
                SPListname = ListName,
                SPViewName = ViewName
            });            
        }
     
        void client_GetSPItemDetailCompleted(object sender, SMIL.Client.WPXAP.SPCommunication.ASMX.GetSPItemDetailCompletedEventArgs e)
        {
            Details = e.Result.SPItemDetail;
        }

        void ob_Click(object sender, RoutedEventArgs e)
        {
            HtmlPage.Window.Navigate(new Uri(ObjectUrl), "_blank");
        }

        void sb_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //HtmlPage.Window.Invoke("ConnectScript", new string[] { ((Button)sender).Tag as string });
                HtmlPage.Window.Invoke("ConnectScript", new string[] { SPItemID });
            }
            catch (Exception ex)
            {
                string msg = string.Empty;
                msg = ex.Message;
                while (ex.InnerException != null)
                {
                    msg += "... Innerexception: " + ex.Message;
                    ex = ex.InnerException;
                }

                MessageBox.Show("Någonting fel vid anrop till Web Part Javascript. Meddelande: " + msg);
            }
        }

        public override void LoadAnimation()
        {
            daw.From = dah.From = 0;
            daw.To = dah.To = 90;
            s.Completed -= UnloadAnimationCompleted;
            s.Completed += LoadAnimationCompleted;
            s.Dispatcher.BeginInvoke(() => s.Begin());
        }

        public override void UnloadAnimation()
        {
            daw.From = dah.From = 90;
            daw.To = dah.To = 0;
            s.Completed -= LoadAnimationCompleted;
            s.Completed += UnloadAnimationCompleted;
            s.Dispatcher.BeginInvoke(() => s.Begin());
        }

        void b0_MouseEnter(object sender, MouseEventArgs e)
        {
            b1.Visibility = b2.Visibility = Visibility.Visible;            
            //b0.Background.Opacity = 1.0;            
        }
   
        void g_MouseLeave(object sender, MouseEventArgs e)
        {
            if (b3.Visibility == Visibility.Visible)
                return;

            //b0.Background.Opacity = 0.6;
            b1.Visibility = b2.Visibility = b3.Visibility = Visibility.Collapsed;
        }

        private bool isSharepointLink(string url)
        {
            return url.Contains("/Forms/") || url.Contains("/Lists/");
        }
    }
}
